#!/usr/bin/env python
# -*- coding: utf-8 -*-
import paramiko
import time
import threading


# 车辆IP地址列表，第一个为主车，其余为从车
ip = [
    "192.168.0.100",
    "192.168.0.101",
]

username = 'wheeltec'
password = 'dongguan'
ip_status = []  # 记录每辆车的状态，初始为"stop"
input_flag = 1


def send_command(ssh, command):
    """发送命令并等待执行完成"""
    try:
        shell = ssh.invoke_shell()
        shell.send(f"DISPLAY=:0 {command}\n")
        time.sleep(6)
        return True
    except Exception as e:
        print(f"发送命令时出错: {e}")
        return False
    finally:
        ssh.close()


def control_onecar(carnub, carip, carcmd):
    """控制单辆车"""
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect(hostname=carip, port=22, username=username, password=password)
    except Exception as e:
        print(f"连接到{carip}时出错: {e}")
        return

    if carcmd == 'open':
        script = "leadercar.sh" if carnub == 1 else "slavecar.sh"
        command = f"bash ~/wheeltec_ros2/src/wheeltec_multi/scripts/{script}"
        if send_command(ssh, command):
            ip_status[carnub - 1] = "open"
    elif carcmd == 'stop':
        command = "bash ~/wheeltec_ros2/src/wheeltec_multi/scripts/killall.sh"
        if send_command(ssh, command):
            ip_status[carnub - 1] = "stop"
    else:
        print("无效的命令，请输入'open'或'stop'")


def control_allcar(carlen, allcarip, carcmd):
    """控制所有车辆"""
    threads = []
    for i in range(carlen):
        t = threading.Thread(target=control_onecar, args=(i + 1, allcarip[i], carcmd))
        threads.append(t)
    for t in threads:
        t.start()
    for t in threads:
        t.join()


def print_allcar_status(carip, carstatus):
    """打印所有车辆状态"""
    print("\n当前所有车辆IP地址及运行状态如下：")
    for i in range(len(carip)):
        car_type = "主车" if i == 0 else "从车"
        print(f"{i + 1}号{car_type}，编号：{i + 1} ip：{carip[i]} 状态：{carstatus[i]}")
    print()


def get_valid_input(prompt, validator, error_msg):
    """获取有效的用户输入"""
    while True:
        user_input = input(prompt)
        if validator(user_input):
            return user_input
        print(error_msg)


def main():
    try:
        # 初始化车辆状态
        for _ in range(len(ip)):
            ip_status.append("stop")

        print_allcar_status(ip, ip_status)

        # 确认IP地址
        makesure = get_valid_input("1.请确认目前使用的主车ip及从车ip无误，有误请修改cmd.py文件的ip变量，并按回车键确认:", 
                                  lambda x: True, "")
        print("正在初始化中，请稍后......")
        control_allcar(len(ip), ip, "stop")
        print_allcar_status(ip, ip_status)

        while True:
            # 选择操作的车辆
            car_count = len(ip)
            car_prompt = f"2.选择你要操作的小车，开启或者结束运行这辆小车的程序\n请输入1-{car_count}的数字（操作所有车可输入0）:"
            car_validator = lambda x: x.isdigit() and 0 <= int(x) <= car_count
            car_error_msg = f"输入无效，请输入0或1-{car_count}的数字"
            thiscarnub = int(get_valid_input(car_prompt, car_validator, car_error_msg))

            # 选择操作命令
            cmd_prompt = "请输入'open'开始运行或'stop'结束运行程序:"
            cmd_validator = lambda x: x in ['open', 'stop']
            cmd_error_msg = "输入无效，请输入'open'或'stop'"
            cmd = get_valid_input(cmd_prompt, cmd_validator, cmd_error_msg)

            if thiscarnub == 0:
                control_allcar(len(ip), ip, cmd)
            else:
                control_onecar(thiscarnub, ip[thiscarnub - 1], cmd)

            print_allcar_status(ip, ip_status)

    except Exception as e:
        print(f"程序运行出错: {e}")
    finally:
        # 程序结束前终止所有程序运行
        print("程序结束，正在停止所有车辆程序...")
        control_allcar(len(ip), ip, "stop")


if __name__ == "__main__":
    main()